package com.newsmanagement.controller.admin;


import com.newsmanagement.domain.pojo.Result;
import com.newsmanagement.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class FileUploadController {

    @Value("${file.upload-path}")
    private String pictureurl;

    /*@PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        //把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        //保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //file.transferTo(new File("C:\\Users\\Administrator\\Desktop\\files\\"+filename));
        String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return Result.success(url);
    }*/

    /*@PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {

        log.info("上传图片");
        // 把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        // 保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 指定本地存储路径
        String localPath = pictureurl + filename;
        file.transferTo(new File(localPath));
        log.info(localPath);
        return Result.success(localPath);
    }*/

   /* @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.error("上传的文件不能为空");
        }

        // 检查文件大小是否超出限制
        long maxSize = 10 * 1024 * 1024; // 限制为10MB
        if (file.getSize() > maxSize) {
            return Result.error("文件大小超出限制，最大支持10MB");
        }

        // 检查文件类型是否合法
        String[] allowedTypes = {"image/jpeg", "image/png", "application/pdf"}; // 允许的文件类型
        if (!Arrays.asList(allowedTypes).contains(file.getContentType())) {
            return Result.error("不支持的文件类型，仅允许JPEG、PNG、PDF格式");
        }

        try {
            // 获取原始文件名并生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error("文件名无效");
            }

            // 防止路径遍历攻击，仅保留文件后缀
            String extension = "";
            int dotIndex = originalFilename.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < originalFilename.length() - 1) {
                extension = originalFilename.substring(dotIndex);
            }

            String filename = UUID.randomUUID().toString() + extension;

            // 使用配置化的存储路径
            String localPath = pictureurl + filename;

            // 确保目录存在
            File dir = new File(pictureurl);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    return Result.error("无法创建存储目录");
                }
            }

            // 将文件保存到本地
            File dest = new File(localPath);
            file.transferTo(dest);

            return Result.success(localPath);

        } catch (IOException e) {
            // 捕获IO异常并返回错误信息
            e.printStackTrace();
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }*/

    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){

        log.info("文件上传");

        try {
            //获取原始文件名称
            String originalFilename = file.getOriginalFilename();
            //不同的图片后缀不一样，所以要获取原始文件名的后缀png，jpg
           /* String[] sp = originalFilename.split(".");
            String extendsion = sp[1];*/

            //获取原始文件名的后缀
            String extendsion = originalFilename.substring(originalFilename.lastIndexOf("."));

            //构造新的文件名称
            String objectName = UUID.randomUUID().toString() + extendsion;

            String filePath = aliOssUtil.upload(file.getBytes(), objectName);


            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return null;

    }
}
